package anc.server.tankshooter.network;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;

/**
 * Lớp tạo Thread để lắng nghe các kết nối từ Client, mỗi Client kết nối tới được tạo 1 Thread riêng để làm việc
 * với Client đó
 * @author WolfNguyen
 *
 */
public class Server {

	int port = 2116;
	ServerSocket mServerSocket;
	Socket mSocket =  new Socket();
	Thread mThread;
	HashMap<Integer, Player> mPlayers = new HashMap<Integer, Player>();
	Match[] mMatch = new Match[9];

	
	public Server() throws IOException
	{
		mServerSocket = new ServerSocket(port);
		System.out.println("CREATE SERVER SUCCESS");
		
		for(int i = 0; i < mMatch.length; i++)
		{
			mMatch[i] = new Match(i);
		}
		
		while (true)
		{
			System.out.println("Waiting for connection...");
			mSocket = mServerSocket.accept();
			Thread mThread = new Thread(new Player(mSocket, this));
			mThread.start();
		}
	}
	
	public boolean putInHashMap(int id, Player player)
	{
		if(!mPlayers.containsKey(id))
		{
			mPlayers.put(id, player);
			return true;
		}
		return false;
	}
	public boolean putInHashMap(int id, Thread thread)
	{
		return false;
	}
	
	/**
	 * Get one match
	 */
	public Match GetMatch(int index)
	{
		return mMatch[index];
	}
	
	/**
	 * Get infomation about one match
	 */
	public String GetMatchString(int index)
	{
		return mMatch[index].getStringValue();
	}
	
	/**
	 * Get infomation about all matchs
	 * @return
	 */
	public String GetAllMatch()
	{
		String value = "";
		for(int i = 0; i < mMatch.length; i++)
		{
			value += mMatch[i].getStringValue();
			if (i < mMatch.length - 1) value += "|";
		}
		return value;
	}// SEND  FOR CLIENT THROUGH dos
	

	/**
	 * 
	 */
	public void SendMatchForAllClient()
	{
		final String value = GetAllMatch();
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				for(Player player: mPlayers.values())
				{
					player.SendAllMatch(value);
				}
			}
		}).start();
	}
	
	/**
	 * Cho Client join vào room
	 * @param roomIndex
	 * @param player
	 * @return
	 */
	public boolean ClientJoinRoom(int roomIndex, Player player)
	{
		return mMatch[roomIndex].JoinPlayer(player);
	}

	
	public void ClientDisconnect(int ID)
	{
		mPlayers.remove(ID);
	}
}
